<?php
namespace haibao\www\business\control;
use haibao\ww\model\filter\Article as ArticleFilter;
use haibao\www\model\filter\ArticleTag as ArticleTagFilter;
use haibao\www\model\filter\ArticleProImage as ArticleProImageFilter;
use haibao\www\model\filter\ArticleProperty as ArticlePropertyFilter;
use haibao\frame\data\query\Condition;
use haibao\www\business\control\ArticleController;

class Base extends \haibao\frame\http\UserControl{
	const CUT_TITLE_LEN = 24;
	const CUT_SHORT_TITLE_LEN = 12;
	/**
	 * 模版的更新时间
	 */
	public $updateTime;
	public $controlId;
	public $isPublish;
	public static $CONTROL_DATA = 'controlData';
	public static $CONTROL_CONTENT = 'content';
	public $tagType;
	public $tagUrl = '';
	
	public function __construct($updateTime,$controlId,$isPublish){
		$this->updateTime = strtotime($updateTime);
		$this->controlId = $controlId;
		$this->isPublish = $isPublish;
		if($this->isPublish){
			$this->setConfig('controlPublish');
		}else{
			$this->setConfig('controlPreview');
		}
	}
	
	/**
	 * 生成HTML路径
	 * @param : String $className
	 */
	public function generateHtmlPath($className){

		$basePath = md5($this->controlId.$className).'.html';
		return str_replace(array('/', '\\'), '/', $basePath);
	}

	/**
	 * 生成html
	 * @param string $path 路径
	 * @param string $content 内容
	 */
	public function generateHtml($path,$content = ''){

		$savePath = $this->getSaveHtmlPath();
		$savePath = $savePath.$path;
		//$this->createDir($savePath);

		if(!file_exists($savePath) || (filemtime($savePath) < $this->updateTime) ){
			file_put_contents($savePath, $content);
			return true;
		}
		return false;
	}
	

	/**
	 * 获取HTML保存路径
	 */
	private function getSaveHtmlPath(){
		if($this->isPublish){
			$path = \haibao\frame\Environment::path().\haibao\cms\Config::CONTROL_HTML_PUBLISH_PATH;
		}else{
			$path = \haibao\frame\Environment::path().\haibao\cms\Config::CONTROL_HTML_PREVIEW_PATH;
		}
		if(!file_exists($path)){
			mkdir($path, 750, true);
		}
		return $path;
		
	}
	
	/**
	 * 创建文件保存路径
	 */
	private function createDir($path){
		return is_writable($path['dirname']) ?: mkdir($path['dirname'], 750, true);
	}
	
	public function getActualData($dataCondition){
		
	}
	public function replaceCDNLink($content,$flag = false){
		return preg_replace_callback("/<img data\-lazy\-src=\"(.*?)\" width=\"(\d+)\" height=\"(\d+)\".*?>/is", 'self::regReplaceUrl', $content);

	}
	
	/**
	 * 替换内容中的img 为mt*
	 */
	public function regReplaceUrl($matches){
		$imgHtml = '';
		$key = \haibao\cms\Config::ENCRYPT_KEY;
		//if(count($matches) != 4) continue;
		
		$height = array_pop($matches);
		$width = array_pop($matches);
		$imageUrl = array_pop($matches);
		$imgHtml = array_pop($matches);

		$staticImageUrl = $this->replaceImageLink($imageUrl,$width,$height);
		$newImgName = md5($staticImageUrl.$key);
		$hasCount = strpos($staticImageUrl, \haibao\cms\Config::STATIC_DOMAIN);
	
		$cdnNum = $this->getHash($newImgName);
		$imgUrl = \haibao\cms\Config::$cdnNewHost[$cdnNum];
		$mtUrl = str_replace(\haibao\cms\Config::STATIC_DOMAIN,$imgUrl,$staticImageUrl);
		
		return strtr($imgHtml,array($imageUrl=>$mtUrl));
	}
	
	/**
	 * 图片替换成static的链接
	 * @param string $imgUrl
	 * @param int $width	宽 600(文章图片最大为600)
	 * @param int $height	高
	 * @param int $quality	质量(0-100)，默认75
	 * @param int $water	是否水印(1打0无)
	 * @return string
	 */
	private function replaceImageLink($imgUrl,$width = 600,$height = 0,$quality = 100,$water = 0){
		$key = \haibao\cms\Config::ENCRYPT_KEY;
		$imgFileName = substr($imgUrl, strrpos($imgUrl, '/')+1);
		$imgName = substr($imgFileName, 0, strrpos($imgFileName, '.'));
		$imgType = substr($imgFileName, strrpos($imgFileName, '.'));
		$condition = '/'.$width.'_'.$height.'_'.$quality.'_'.$water.'/'.$imgName.'/';
		$newUrl = '';
		$isHasUploads = strpos($imgUrl,\haibao\cms\Config::IMAGE_UPLOAD_BASE_PATH);
		if($isHasUploads === false){
			$config = \haibao\cms\Config::getFrameConfig();
			$newImgName = str_replace($config[\haibao\frame\http\HttpEnvironment::DOMAIN], '', $imgUrl);
			$newUrl = \haibao\cms\Config::STATIC_DOMAIN.$condition.$newImgName;
		} else {
			$newImgName = md5($condition.$key);
			$newUrl = \haibao\cms\Config::STATIC_DOMAIN.$condition.$newImgName.$imgType;
		}
		return $newUrl;
	}
	
	private function getHash($key,$isNew = true){
		$hash = crc32($key) >> 16 & 0xffff;
		$cdnHostArr = array(
				'http://mt0.haibao.cn/img',
				'http://mt2.haibao.cn/img',
				'http://mt4.haibao.cn/img',
				'http://mt6.haibao.cn/img',
		);
		if(!$isNew){
			$cdnHostArr = array(
					'http://cdn0.hbimg.cn',
					'http://cdn2.hbimg.cn',
					'http://cdn4.hbimg.cn',
					'http://cdn6.hbimg.cn',
			);
		}
		return sprintf('%01s',$hash % count($cdnHostArr));
	}
	
	
	/**
	 * 按照固定长度切割内容
	 * @param : String $title 被切割内容
	 * @param : $len 切割长度
	 */
	public function cutTitle($title,$cutLen){
		$titleLen = mb_strlen($title,'utf-8');
		$final = '';
		$len = 1;
		if($titleLen > $cutLen){
			/* $enStr = 1;
			for($i=0;$i<$titleLen;$i++){
				if($len <= $cutLen){
					$temp = mb_substr($title, $i,1,'utf-8');
					if (!preg_match("/^[\x4e00-\x9fa5]+$/",$temp)) {
						$final .= $temp;
					} else {
						if($enStr <= 3){
							$final .= $temp;
							echo $final."-----{$enStr}<br/>";
							$enStr++;
						}else{
							$enStr = 1;
						}
					}
				}
			}
			echo $final;
			exit; */
			$title = mb_substr($title,0,$cutLen,'utf-8');
		}
		return $title;
	}
	
	/**
	 * 时间格式化
	 * @param : $date 时间（Y-m-d H:i:s）
	 * @param : $type 格式化结果 1（今天/昨天 10:25）
	 */
	public function formatDate($date,$type = 1){
		
		$finalDate = '';
		$strTime = strtotime($date);
		$today = date('j');
		if($type == 1){
			$day = date('j',$strTime);
			$hour = date('H:i',$strTime);
			$diff = $today - $day;
			if($diff == 0){
				$finalDate = '今天'.$hour;
			}elseif($diff == 1){
				$finalDate = '昨天'.$hour;
			}else{
				$finalDate = date('Y-m-d H:i',$strTime);
			}
		}
		return $finalDate;
	}
	
	/**
	 * 获取文章标签
	 * @param : Array $articleId 
	 * @param : Boolure $isPrimary  是否只返回主标签
	 */
	public function getArticleTag($articleId,$isPrimary = true){
		
		$articleTagFilter = new ArticleTagFilter();

		$articleTagFilter->select(
				array(
					ArticleTagFilter::CONDITION_FIELD_NAME_ARTICLE_ID,
					ArticleTagFilter::CONDITION_FIELD_NAME_TAG_ID,
					ArticleTagFilter::CONDITION_FIELD_NAME_PARENT_ID,
					ArticleTagFilter::CONDITION_FIELD_NAME_IS_PRIMAIY,
				)
		);
		if($isPrimary) {
			$articleTagFilter->where(ArticleTagFilter::CONDITION_FIELD_NAME_IS_PRIMAIY,Condition::CONDITION_EQUAL,\haibao\cms\model\data\Article::PUBLISHED_YES);
		}
		$articleTagFilter->where(ArticleTagFilter::CONDITION_FIELD_NAME_ARTICLE_ID,Condition::CONDITION_IN,$articleId);

		$article = new \haibao\cms\data\Article();
		$articleTag = $article->getAll($articleTagFilter);
		$articleTagArr = array();
		foreach($articleTag as $key=>$tag){
			
			if(isset($articleTagArr[$tag->ArticleId])) {
				$articleTagArr[$tag->ArticleId][] = $tag->TagId;
			}else{
				$articleTagArr[$tag->ArticleId] = array();
				$articleTagArr[$tag->ArticleId][] = $tag->TagId;
			}
		}
		if($isPrimary){
			$arr = array();
			foreach ($articleTagArr as $key=>$value) {
				$arr[$key] = array_pop($value);
			}
			return $arr;
		}
		return $articleTagArr;
	}
	
	public function initArticleControl(){

		return ArticleController::initArticleControl();
	}
	/**
	 * 获取文章返回信息
	 * @param Int $queryType 查询的类型
	 */
	public function getArticleControl($queryType,$queryCondition){
		
		$articleControl = ArticleController::initArticleControl();

		if(isset($queryCondition['isPrimaryTag'])){
			$isPrimaryTag = true;
		}else{
			$isPrimaryTag = false;
		}
		if(isset($queryCondition['isReturnTag'])){
			$isReturnTag = true;
		}else{
			$isReturnTag = false;
		}
		
		if(!isset($queryCondition['isParentTag'])){
			$isParentTag = true;
		}else{
			$isParentTag = false;
		}
		
		switch($queryType){
			case ArticleController::QUERY_TYPE_CHANNEL:
				
				$articleControl->setLimit($queryCondition['limit']);
				$articleControl->setLevel($queryCondition['level']);
				
				$articleControl->setIsArticleTag($queryCondition['isTag'],$this->tagType,$this->tagUrl,$isPrimaryTag,$isReturnTag,$isParentTag);
				if($queryCondition['isProImage']){
					$articleControl->setIsProImage($queryCondition['isProImage'],$queryCondition['proImageLevel']);
				}else{
					$articleControl->setIsProImage($queryCondition['isProImage']);
				}
				return $articleControl->getChannelArticleAndAtiasByChannel();
				
				break;
			case ArticleController::QUERY_TYPE_CLICK:
				$articleControl->setLimit($queryCondition['limit']);
				$articleControl->setIsArticleTag($queryCondition['isTag'],$this->tagType,$this->tagUrl,$isPrimaryTag);
				if($queryCondition['isProImage']){
					$articleControl->setIsProImage($queryCondition['isProImage'],$queryCondition['proImageLevel']);
				}else{
					$articleControl->setIsProImage($queryCondition['isProImage']);
				}
				return $articleControl->getChannelArticleAndAtiasByClick();
			default:
				break;
			
		}
	}
}

